package cc.idoone.handlermapping.version;

import org.springframework.web.servlet.mvc.condition.RequestCondition;

import javax.servlet.http.HttpServletRequest;

/**
 * @auther hemj
 * @since 2018/5/9
 */
public class ApiVersionCondition implements RequestCondition<ApiVersionCondition> {
	// http 请求头中的接口版本名称定义
	private final static String HEAD_API_VERSION = "Api-Version";

	private int apiVersion;

	public ApiVersionCondition(int apiVersion) {
		this.apiVersion = apiVersion;
	}

	public ApiVersionCondition combine(ApiVersionCondition other) {
		// 采用最后定义优先原则，则方法上的定义覆盖类上面的定义
		return new ApiVersionCondition(other.getApiVersion());
	}

	public ApiVersionCondition getMatchingCondition(HttpServletRequest request) {
		try {
			String apiVersion = request.getHeader(HEAD_API_VERSION);
			if (apiVersion == null) {
				apiVersion = request.getParameter("v");
			}
			if (apiVersion != null) {
				Integer version = Integer.valueOf(apiVersion);
				if (version >= this.apiVersion) // 如果请求的版本号大于配置版本号， 则满足
					return this;
			}
		} catch (NumberFormatException e) {
			e.printStackTrace(System.err);
		}
		return null;
	}

	public int compareTo(ApiVersionCondition other, HttpServletRequest request) {
		// 优先匹配最新的版本号
		return other.getApiVersion() - this.apiVersion;
	}

	public int getApiVersion() {
		return apiVersion;
	}

}